<template>
    <el-dialog :close-on-click-modal="false"  ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="80%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <template v-if="addEditFlag !== 'lookView'">
                <el-form-item label="模板名称" prop="templateName">
                    <el-input v-model="ruleForm.templateName" class="w100p" clearable placeholder="请输入模板名称"></el-input>
                </el-form-item>
                <el-form-item label="检验类型" prop="checkStageId">
                    <el-select v-model="ruleForm.checkStageId" class="w100p" @change="handleCheckStage" clearable
                        filterable placeholder="请选择检验类型">
                        <el-option v-for="item, index in phaseList" :key="index" :label="item.checkStageName"
                            :value="item.checkStageId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="检验范畴科目" prop="checkScopeIdList">
                    <div class="chooseScopeType">
                        <el-select class="select2" v-model="ruleForm.checkScopeIdList" multiple
                            @change="handleCheckScope" collapse-tags clearable filterable placeholder="请选择检验科目">
                            <el-option
                                v-show="!ruleForm.selectScopeTypeName || ruleForm.selectScopeTypeName == item.scopeTypeName"
                                v-for="item, index in newSubjectList" :key="index"
                                :label="`${item.checkScopeName}${item.checkStandard}`"
                                :value="item.checkScopeId"></el-option>
                        </el-select>
                        <el-select class="select1" v-model="ruleForm.selectScopeTypeName" clearable placeholder="筛选范畴">
                            <el-option v-for="item, index in scopeList" :key="index" :label="item.scopeTypeName"
                                :value="item.scopeTypeName"></el-option>
                        </el-select>
                    </div>
                </el-form-item>
            </template>
            <el-form-item label="模板总分">
                <span class="totalScore">{{ totalScore }}分</span>
                <span class="error">注：模板总分必须为100分</span>
            </el-form-item>
            <el-form-item label="配置分数">
                <div class="w100p tableDataModule">
                    <TableData :tableThead="tableThead" :dataList="detailList" :loading="loading">
                        <template v-slot:setSocre="{ row }">
                            <el-input v-show="addEditFlag !== 'lookView'" type="number"
                                @change="handleChangeSetSocre($event, row)" v-model="row.socre" class="w100p" clearable
                                placeholder="请输入分数"></el-input>
                            <span v-show="addEditFlag == 'lookView'">{{ row.socre }}</span>
                        </template>
                        <template v-slot:option="{ row }">
                            <span v-show="addEditFlag !== 'lookView'" @click="handleDelItem(row)"
                                class="error">删除</span>
                            <span v-show="addEditFlag == 'lookView'">/</span>
                        </template>
                        <template v-slot:oneVoteDownFlag="{ row }">
                            <el-switch :disabled="addEditFlag == 'lookView'" v-model="row.oneVoteDownFlag"
                                active-color="#13ce66" inactive-color="#ff4949">
                            </el-switch>
                        </template>
                    </TableData>
                </div>
            </el-form-item>
            <!-- <el-form-item label="检验范畴" prop="checkScopeTypeId">
                <el-select v-model="ruleForm.checkScopeTypeId" class="w100p" clearable
                    filterable placeholder="请选择检验范畴">
                    <el-option v-for="item, index in scopeList" :key="index" :label="item.scopeTypeName"
                        :value="item.checkScopeTypeId"></el-option>
                </el-select>
            </el-form-item> -->
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import TableData from '@/components/TableData';
import checkScoreConfig from '@/api/basicInformation/checkScoreConfig.js';
export default {
    components: { TableData },
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        scopeList: {
            type: Array,
            default: () => {
                return []
            }
        },
        phaseList: {
            type: Array,
            default: () => {
                return []
            }
        },
        subjectList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        return {
            totalScore:0,
            resetTable: true,
            loading: false,
            addEditName: '添加',
            addEditApi: checkScoreConfig.add,
            ruleForm: {},
            rules: {
                templateName: [
                    { required: true, message: '请选择检验范畴', trigger: 'change' }
                ],
                checkStageId: [
                    { required: true, message: '请输入检验科目', trigger: 'change' }
                ],
                checkScopeIdList: [
                    { required: true, message: '请输入检验标注', trigger: 'change' }
                ]
            },
            tableThead: [
                { isShow: true, label: '范畴名称', prop: 'scopeTypeName', minWidth: '20' },
                { isShow: true, label: '科目名称', prop: 'checkScopeName', minWidth: '20' },
                { isShow: true, label: '检验标准', prop: 'checkStandard' },
                { isShow: true, label: '检验分数', slotName: 'setSocre', minWidth: '30' },
                { isShow: true, label: '是否一票否决', slotName: 'oneVoteDownFlag', minWidth: '30' },
                { isShow: true, label: '操作', slotName: 'option', minWidth: '20' },
            ],
            dataList: [],
            detailList: [],
            scopeObj: {},
            selectList: [],
            newSubjectList: []
        }
    },
    computed: {

    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm()
                this.addEditApi = checkScoreConfig.add
                this.addEditName = '添加'
            } else if (this.addEditFlag == 'edit' || this.addEditFlag == 'lookView') {
                this.ruleForm = { ...this.data }
                this.addEditApi = checkScoreConfig.edit
                this.addEditName = '编辑';
            }
            this.addEditName = this.addEditFlag == 'lookView' ? '查看' : this.addEditName;
            this.detailList = this.ruleForm.detailList || []
            this.$set(this.ruleForm, 'detailList', this.detailList.map(e => {
                return e.checkScopeId
            }))
            this.scopeList.forEach(e => {
                this.scopeObj[e.checkScopeTypeId] = e.scopeTypeName
            })
            this.newSubjectList = []
            this.subjectList.forEach(e => {
                this.scopeObj[e.checkScopeTypeId] && this.newSubjectList.push({ ...e, scopeTypeName: this.scopeObj[e.checkScopeTypeId] })
            })
            let checkScopeIdList = this.detailList.map(e => {
                return e.checkScopeId
            });
            this.$set(this.ruleForm, 'checkScopeIdList', checkScopeIdList || []);
            this.gettotalScore(this.detailList)
        },
        handleCheckScope(list) {
            let newList = this.newSubjectList.filter(e => {
                return list.includes(e.checkScopeId) && e.scopeTypeName
            });
            newList.forEach(e => {
                let checkScopeId = e.checkScopeId;
                e = this.detailList.find(info => {
                    return info.checkScopeId == checkScopeId
                }) || e;
            });
            let checkList = newList.map(e => {
                let checkScopeId = e.checkScopeId;
                e.socre = e.socre ? e.socre : 1;
                return this.detailList.find(info => {
                    return info.checkScopeId == checkScopeId
                }) || JSON.parse(JSON.stringify(e));
            });
            this.detailList = []
            checkList.forEach(item => {
                this.detailList.push(item)
            })
            this.resetTable = false;
            this.$nextTick(() => {
                this.gettotalScore(this.detailList)
                this.resetTable = true;
            })
        },
        gettotalScore(list) {
            this.totalScore = list.reduce((sum, item) => sum + Number(item.socre), 0);
        },
        handleChangeSetSocre(e, row) {
            if (!(e > 0 && e % 1 == 0)) {
                row.socre = Math.abs(e).toFixed(0);
                row.socre = row.socre > 0 ? row.socre : 1;
                this.$message.warning('请输入大于0的有效整数');
            }
            
            this.gettotalScore(this.detailList);
        },
        handleDelItem(row) {
            let checkScopeId = row.checkScopeId
            this.detailList = this.detailList.filter(e => {
                return e.checkScopeId !== checkScopeId
            })
            this.ruleForm.checkScopeIdList = this.ruleForm.checkScopeIdList.filter(id => {
                return id !== checkScopeId
            })
            this.gettotalScore(this.detailList);
            console.log(this.ruleForm.checkScopeIdList)
        },
        handleCheckStage(e) {
            let rut = this.phaseList.find(item => { return item.checkStageId == e })
            this.$set(this.ruleForm, 'checkStageName', rut?.checkStageName || '')
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.detailList.forEach(e => {
                        e.oneVoteDownFlag = !!e.oneVoteDownFlag
                    })
                    this.addEditApi({ ...this.ruleForm, detailList: this.detailList }).then(res => {
                        let msg = res.code == 1 ? '操作成功' : '操作失败'
                        this.$message[res.code == 1 ? 'success' : 'warning'](res.msg || msg)
                        res.code == 1 && this.cancel();
                    }).catch(err => {
                        console.log(err)
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.tableDataModule {
    height: 400px;
}

.chooseScopeType {
    display: flex;
    justify-content: flex-start;

    .select1 {
        width: 10%;
    }

    .select2 {

        width: 90%;
    }
}
.totalScore{
    padding-right: 50px;
}
.error {
    cursor: pointer;
    color: #ff0000;
    text-align: left;
}
</style>